#!/usr/bin/env python


import sys
sys.path.insert(0, '../')
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meiduo.settings")
import django
django.setup()


import os
from apps.contents.models import ContentCategory
from meiduo import settings
from utils.goodsutils import get_categories
from django.template import loader

def haha():
    try:
        categories = get_categories()
    except Exception as e:
        print(e)
        return {'code': 1, 'errmsg': 'get data error'}

    # 广告内容
    contents = {}
    content_categories = ContentCategory.objects.all()
    for cat in content_categories:
        contents[cat.key] = cat.content_set.filter(status=True).order_by('sequence')

    # 渲染模板

    context = {
        'categories': categories,
        'contents': contents
    }
    # 获取首页模板文件
    template = loader.get_template('index.html')
    # 渲染首页html字符串
    html_text = template.render(context)
    # 将首页html字符串写入到指定目录，命名'index.html'
    file_path = os.path.join(os.path.dirname(settings.BASE_DIR), 'front_end_pc/index.html')
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(html_text)
    print("生成html文件成功")


if __name__ == '__main__':
    haha()
